# -*- coding: utf-8 -*-
import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,execjs
from common.helper import Helper
from urllib.parse import urlencode


class Spider( object ):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "华夏常青树重大疾病保险"

    # 生产产品数据
    def genProductInfo(self):
        plan = {
            "planA":{
                # 年龄段
                "year":[str(i) for i in range(0,41)],
                #性别
                "gender":["M","F"],
                #保额
                "money":["50000","100000","200000","300000","400000","500000"],
                #交费间隔
                "interval":["5","10","15","20"],
                #保障期限
                "expire":["终身"],
                #交费类型
                "payType":["年交"],

            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000","300000"],
                # 交费间隔
                "interval": ["5", "10", "15", "20"],
                # 保障期限
                "expire": ["终身"],
                # 交费类型
                "payType": ["年交"],

            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(46, 50)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000"],
                # 交费间隔
                "interval": ["5", "10", "15", "20"],
                # 保障期限
                "expire": ["终身"],
                # 交费类型
                "payType": ["年交"],

            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000"],
                # 交费间隔
                "interval": ["5", "10", "15"],
                # 保障期限
                "expire": ["终身"],
                # 交费类型
                "payType": ["年交"],

            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(56, 61)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000"],
                # 交费间隔
                "interval": ["5", "10"],
                # 保障期限
                "expire": ["终身"],
                # 交费类型
                "payType": ["年交"],

            }

        }
        for k in plan:
            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["interval"],plan[k]["expire"],plan[k]["payType"]):
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5]
                ))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5]
                ) )
    #执行爬虫
    def requestJson(self,dt=None):

        data = {
            "bbirthday": dt["year"],
            "jiaofeiqijian": dt["interval"],
            "sex": "男" if dt["gender"] == "M" else "女",
        }
        payload = urlencode(data).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and r.json()["success"] == "true":

            data = {
                "money":str(int(int(dt["money"])/10000)),
                "rate":r.json()["value"]
            }
            price = Helper.decimalParse( self.calcPrenium( data ) )
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:

            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d/"%dt["id"])
    #计算保险价格
    def calcPrenium(self,data ):

        js = '''
            function t( data ) {
                var e = 0;
                e = 1e4 * data["money"] ;
                var i = e / 1e3 * data["rate"]
                t = Math.round(100 * i) / 100;
                
                return t ;
                }
            '''
        cxt = execjs.compile( js )
        price = cxt.call("t",data )
        return price


    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":1
            }
            self.mysql.updateTask( data )

            self.requestJson( dt )